<?php

namespace MoChat\App\Statistic\Action\Binding;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Sales\Constants\SalesTaskStatusCode;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\App\Sales\Contract\WorkDepartmentContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 会员绑定统计
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SalesClientTaskContract
     */
    protected $salesTaskService;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticBinding/list", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $list = Db::table('work_employee as employee')
            ->join('work_contact_employee as pivot', 'pivot.employee_id', '=', 'employee.id')
            ->leftJoin('work_department as dept', 'dept.id', '=', 'employee.main_department_id')
            ->leftJoin('client as client', 'client.work_employee_id', '=', 'employee.id')
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('client.created_at', [$data['startTime'], $data['endTime']]);
                $query->whereBetween('pivot.created_at', [$data['startTime'], $data['endTime']]);
            })
            ->when(!empty($data['deptId']), function ($query) use ($data) {
                $query->where('dept.id', $data['deptId']);
            })
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', $data['employeeId']);
            })
            ->select([
                'employee.id',
                'employee.name',
                'dept.name as deptName',
                Db::raw('COUNT(DISTINCT mc_pivot.contact_id) as wechatCount'),
                Db::raw('COUNT(DISTINCT mc_client.id) as clientCount'),
            ])->groupBy(['employee.id'])->when(!empty($data['orderBy']),function ($query)use($data){
                $orderString='';
                $data['orderBy']=json_decode($data['orderBy'],true);
                foreach ($data['orderBy'] as $key=>$datum){
                    if ($datum){
                        $datum=$datum=='ascend'?'asc':'desc';
                        $orderString.=$orderString?','.$key.' '.$datum:$key.' '.$datum;
                    }
                }
                if ($orderString){
                    $query->orderByRaw($orderString);
                }
            })->paginate();
        $list || $list = collect([]);
        $list=$list->toArray();
        $list['wechatTotalCount']=array_sum(array_column($list['data'],'wechatCount'));
        $list['clientTotalCount']=array_sum(array_column($list['data'],'clientCount'));
        return $list;
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'page' => 'required|integer',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'page.required' => '分页参数错误',
            'page.integer' => '分页参数错误',
        ];
    }
}
